package com.bckj.fastboot.core.util;

import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class LambdaUtils {

    private static final ConcurrentHashMap<Class<?>, LambdaMeta> CLASS_LAMBDA_CACHE = new ConcurrentHashMap<>();

    /**
     * 关键在于这个方法
     */
    public static LambdaMeta getSerializedLambda(Serializable fn) {
        return CLASS_LAMBDA_CACHE.computeIfAbsent(fn.getClass(), key -> {
            LambdaMeta lambda = null;
            try {
                Method method = fn.getClass().getDeclaredMethod("writeReplace");
                method.setAccessible(Boolean.TRUE);
                lambda = new LambdaMeta((SerializedLambda) method.invoke(fn));
            } catch (Exception e) {
                log.error("LambdaUtils getSerializedLambda error", e);
            }
            return lambda;
        });
    }
}
